package arithmetic1.tree.binaryTree;

/*
    顺序二叉树的特点:
        1.索引为n的节点左子节点索引为2n+1
        2.索引为n的节点右子节点索引为2n+2
        3.索引为n的节点父节点索引为(n-1)/2
    要求:给定一个数组{1,2,3,4,5,6,7},要求把该数组以二叉树的先序中序后序三种方式遍历
 */
public class OrderBinaryTree {
    private int arr[];

    public OrderBinaryTree(int[] arr) {
        this.arr = arr;
    }

    //先序遍历
    public void perOrder(int root){
        if(root>=0 && root<=arr.length-1){
            System.out.print(arr[root]+"\t");
            //向左遍历
            perOrder(2*root+1);
            //向右遍历
            perOrder(2*root+2);
        }
    }
    public void perOrder(){
        if(arr!=null){
            perOrder(0);
        }
    }

    //中序遍历
    public void infixOrder(int root){
        if(root>=0 && root<=arr.length-1){
            //向左遍历
            infixOrder(2*root+1);
            System.out.print(arr[root]+"\t");
            //向右遍历
            infixOrder(2*root+2);
        }
    }
    public void infixOrder(){
        if(arr!=null){
            infixOrder(0);
        }
    }

    //后序遍历
    public void afterOrder(int root){
        if(root>=0 && root<=arr.length-1){
            //向左遍历
            afterOrder(2*root+1);
            //向右遍历
            afterOrder(2*root+2);
            System.out.print(arr[root]+"\t");
        }
    }
    public void afterOrder(){
        if(arr!=null){
            afterOrder(0);
        }
    }

    public static void main(String[] args) {
        int arr[]={1,2,3,4,5,6,7};
        OrderBinaryTree orderBinaryTree=new OrderBinaryTree(arr);
        System.out.println("先序遍历");
        orderBinaryTree.perOrder();
        System.out.println();
        System.out.println("中序遍历");
        orderBinaryTree.infixOrder();
        System.out.println();
        System.out.println("后序遍历");
        orderBinaryTree.afterOrder();
    }
}
